package com.mundus.game;

import org.lwjgl.opengl.*;
import org.lwjgl.util.Color;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
import org.lwjgl.util.vector.Vector4f;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;

import com.mundus.engine.Engine;
import com.mundus.engine.assets.vertex.VertexDrawable;
import com.mundus.engine.assets.vertex.VertexFactory;
import com.mundus.engine.assets.vertex.VertexPosCol;
import com.mundus.engine.assets.vertex.VertexPosTex;
import com.mundus.engine.resources.Shader;
import com.mundus.engine.resources.ShaderLoader;
import com.mundus.world.observer.Observer;

public class Game extends Engine{
	
	public Game(){
		super("Mundus Engine");
	}
	
	Observer camera;
	VertexDrawable quad;
	Shader shader;
	Texture tex;
	
	/**
	 * Load game components here
	 */
	@Override
	public void init() throws Exception {
		VertexFactory<VertexPosTex> v = new VertexFactory<VertexPosTex>();
		v.addVertex(new VertexPosTex(new Vector3f(-1,1,0),new Vector2f(0,0)));
		v.addVertex(new VertexPosTex(new Vector3f(1,1,0),new Vector2f(1,0)));
		v.addVertex(new VertexPosTex(new Vector3f(1,-1,0),new Vector2f(1,1)));
		v.addVertex(new VertexPosTex(new Vector3f(-1,-1,0),new Vector2f(0,1)));;
		
		v.addIndices(new byte[]{0,1,2,2,3,0});
		
		quad = v.genVertexDrawable();		
		
		tex = TextureLoader.getTexture("PNG",  ResourceLoader.getResourceAsStream("res\\diffuse.png"));
		
		camera = new Observer(new Vector3f(0,0,200),new Vector4f(0, 1, 0, 0), (float)Math.PI/4);	
		
		shader = ShaderLoader.getShader("basic_vert.glsl", "basic_frag.glsl",new String[]{"in_Position","in_TexCoord"});
		
	}

	/**
	 * Update game components here
	 */
	@Override
	public void update(int delta) throws Exception{	
		camera.update();
	}

	/**
	 * Render game components here
	 */
	@Override
	public void render(int delta) throws Exception{		
		GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
		GL11.glEnable(GL11.GL_BLEND);
		GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);	
		
		shader.apply();		
		shader.setMatrix("projection",camera.getProjection());
		shader.setMatrix("view", camera.getView());
		Matrix4f m = new Matrix4f();
		m = Matrix4f.translate(new Vector3f(0, 0, 0),m,m);
		shader.setMatrix("model", m);		
		shader.setTexture("tex_diff", tex, GL13.GL_TEXTURE0);
		
		quad.draw();
		
		shader.remove();
	}

	/**
	 * Unload game components here
	 */
	@Override
	public void destroy() {
	}

}
